# vim: ai ts=2 sts=2 et sw=2

import bisect
import weakref

import pygame
from pygame.locals import *

import widget

class Dragger(widget.Widget):
  def __init__(self, left, top, width, height):
    widget.Widget.__init__(self, left, top, width, height)

    self.drag = False

  def handleEvent(self, event):
    if widget.Widget.handleEvent(self, event):
      return True

    if self.visible:
      if event.type == MOUSEMOTION and self.drag == True:
        return self.onMouseMotion(event)

    return False

  def onMouseMotion(self, event):
    if self.drag:
      self.parent().move(event.rel)
    return True

  def onMouseButtonUp(self, event):
    self.drag = False
    return True

  def onMouseButtonDown(self, event):
    self.drag = True
    return True

  def onDraw(self, surface):
    pygame.draw.rect(surface, (255, 255, 255), self.screenRect, 1)

class Container(widget.Widget):
  """
  """
  def __init__(self, left, top, width, height):
    widget.Widget.__init__(self, left, top, width, height)
    self.containedWidgets = []

  def show(self):
    widget.Widget.show(self)
    i = 0
    while i < len(self.containedWidgets):
      self.containedWidgets[i].show()
      i += 1

  def hide(self):
    i = 0
    while i < len(self.containedWidgets):
      self.containedWidgets[i].hide()
      i += 1
    widget.Widget.hide(self)

  def move(self, pos):
    widget.Widget.move(self, pos)

    i = 0
    while i < len(self.containedWidgets):
      self.containedWidgets[i].move(pos)
      i += 1

  def onDraw(self, surface):
    i = 0
    while i < len(self.containedWidgets):
      self.containedWidgets[i].draw(surface)
      i += 1

  def add(self, widget):
    widget.parent = weakref.ref(self)
    widget.screenRect.move_ip(self.rect.left, self.rect.top)
    widget.zorder = len(self.containedWidgets)
    bisect.insort(self.containedWidgets, widget)

  def remove(self, widget):
    widget.screenRect = widget.rect
    widget.zorder = 0
    self.containedWidgets.remove(widget)

  def handleEvent(self, event):
    """
    Asks all of the contained widgets to handle an event and then tries
    to the handle the event itself if possible.
    """
    # see if any of the contained widgets (in reverse zorder) handle this event
    i = len(self.containedWidgets) - 1
    while i >= 0:
      if self.containedWidgets[i].handleEvent(event):
        return True
      i -= 1

    # otherwise, try to handle it ourself
    return widget.Widget.handleEvent(self, event)
